﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

public interface IClient
{
    void sendCmd(Cmd cmd);

    void Receive(Cmd cmd);

}

public interface IServer
{

    void Connect(IClient client);

    void sendCmd(Cmd cmd);

    void Receive(Cmd cmd);
}

public class Nets : Singleton<Nets>, IClient
{

    IServer _server;
    Dictionary<Type, Action<Cmd>> _parser = new Dictionary<Type, Action<Cmd>>();

    //消息的缓存
    List<Cmd> _cache = new List<Cmd>();

    private bool _pause;

    public bool Pause
    {
        get { return _pause; }
        set
        {
            _pause = value;
            if (value == false)
            {
                Receive(null);
            }
        }

    }

    public Nets()
    {
        _parser.Add(typeof(RoleListCmd), UserData.OnRoleList);
        _parser.Add(typeof(MainRoleThisidCmd), RoleMgr.OnMainRoleThisid);
        _parser.Add(typeof(EnterMapCmd), SceneMgr.OnEnterMap);
        _parser.Add(typeof(CreateSceneRole), RoleMgr.OnCreateSceneRole);
    }

    public void ConnectServer(Action successCallBack, Action failedCallBack)
    {
        Debug.Log("连接成功");
        _server = Server.instance;
        _server.Connect(this);

        //if (true)
        //{
            if (successCallBack != null)
            {
                successCallBack();
            }
        //}
        //else
        //{
        //    if (failedCallBack != null)
        //    {
        //        failedCallBack();
        //    }

        //}
    }

    public void Receive(Cmd cmd)
    {
        Debug.Log("收到服务器消息" + cmd + " 当前状态 " + Pause);
        if (cmd != null)
        {
            _cache.Add(cmd);
        }

        if (Pause)//如果是阻塞状态就只接受消息，不解析
        {
            return;
        }
        //如果是非阻塞状态
        foreach (var itemCmd in _cache)
        {
            Action<Cmd> func;
            if (_parser.TryGetValue(itemCmd.GetType(), out func))
            {
                if (func != null)
                {
                    func(itemCmd);
                }
            }
        }
        _cache.Clear();
    }

    public void sendCmd(Cmd cmd)
    {
        _server.Receive(cmd);
    }

    public static bool CheckCmd(Cmd cmd, Type targetType)
    {
        if (cmd.GetType() != targetType)
        {
            Debug.LogError(string.Format("需要{0},但是收到了{1}", targetType, cmd.GetType()));
            return false;
        }

        return true;
    }
}
